package base.service.impl;

import base.pojo.Account;
import base.pojo.IPlog;
import base.pojo.LoginInfo;
import base.pojo.UserInfo;
import base.service.IAccountService;
import base.service.IUserInfoService;
import base.service.IiPlogService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import common.Const;
import common.ServerResponse;
import base.mapper.LoginInfoMapper;
import common.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import base.service.ILoginInfoService;
import util.MD5;
import util.PageUtil;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 登录/注册相关服务
 * @author LiuZhi
 */
@Service
public class LoginInfoServiceImpl implements ILoginInfoService
{
    @Autowired
    private LoginInfoMapper     loginInfoMapper ;
    @Autowired
    private IAccountService     iAccountService ;
    @Autowired
    private IUserInfoService    iUserInfoService;
    @Autowired
    private IiPlogService       iiPlogService   ;
    public ServerResponse<String> register(String username, String password) throws Exception
    {
        int count =loginInfoMapper.getCountByUserName(username);

        if(count <= 0)
        {
            LoginInfo li = new LoginInfo()                  ;
            li.setUsername           (username)             ;
            password     = MD5.encode(password)             ;
            li.setPassword           (password)             ;
            li.setState              (Const.STATE_NORMAL )  ;
            li.setUserType           (Const.USER_CUSTOMER)  ;
            loginInfoMapper.insert   (li)                   ;
            if(li.getId()   !=  null &&  li.getId() !=  0)
            {
                //添加账户信息
                Account     account     =   new Account()   ;
                account.setId(li.getId())                   ;
                iAccountService.add(account)                ;
                //添加用户信息
                UserInfo    userInfo    =   new UserInfo()  ;
                userInfo.setId(li.getId())                  ;
                iUserInfoService.add(userInfo)              ;
            }else
                {
                    return ServerResponse.createByErrorMsg  ("用户注册失败")  ;
                }
            return ServerResponse.createBySuccessMsg        ("用户注册成功")  ;
        }else
            {
                return ServerResponse.createByErrorMsg      ("用户已存在")    ;
            }

    }

    public ServerResponse<String> checkUsername(String username)
    {
        int count    =  loginInfoMapper.getCountByUserName(username) ;

        if( count    <= 0)
        {
            return ServerResponse.createBySuccess()                  ;
        }
        return  ServerResponse.createByErrorMsg("用户已存在")         ;
    }

    public ServerResponse login(String username, String password, String remoteAddr,int userType)
    {
        password            = MD5.encode(password)                       ;
        LoginInfo currentLI = loginInfoMapper.login(username,password
                                                            ,userType)   ;
        Map       map       = iiPlogService.getErrorLog(username)        ;
        //添加日记  Begin
        IPlog     iPlog     = new IPlog()                                ;
        iPlog.setUserName   (username)                                   ;
        iPlog.setLoginTime  (new Date())                                 ;
        iPlog.setIp         (remoteAddr)                                 ;
        iPlog.setUserType   (userType)                                   ;
        //添加日记  End
        if(!(boolean)map.get("isSuccess"))
        {
           return ServerResponse.createByErrorMsg((String)map.get("msg"));
        }
        if (currentLI != null)
        {
            UserContext.putCurrentUser              (currentLI)          ;
            iPlog.setState                          (Const.STATE_SUCCESS);
            iiPlogService.save                      (iPlog)              ;
            Integer ErrorNumber = (Integer) map.get("errorNumber")       ;
            if(ErrorNumber  !=  null  &&  ErrorNumber !=  0 )
            {
                updateErrorNumber(currentLI.getId())                     ;
            }
            return ServerResponse.createBySuccessMsg("登录成功" )        ;
        }
        iPlog.setState                        (Const.STATE_ERROR)        ;
        iiPlogService.save                    (iPlog)                    ;
        addErrorNumber(username)                                         ;
        return ServerResponse.createByErrorMsg("用户名或密码不正确")      ;
    }

    public void updateErrorNumber(Long id)
    {
        loginInfoMapper.updateErrorNumber(id)                            ;
    }

    public void addErrorNumber(String username)
    {
        loginInfoMapper.addErrorNumber(username)                         ;
    }

    public void checkAdmin()
    {
        int count =  loginInfoMapper.getCountByUserType(Const.USER_MANAGE);
        if( count == 0 )
        {
            LoginInfo loginInfo = new LoginInfo()                   ;
            loginInfo.setUsername(Const.ADMIN_USERNAME)             ;
            loginInfo.setPassword(MD5.encode(Const.ADMIN_PASSWORD)) ;
            loginInfo.setUserType(Const.USER_MANAGE)                ;
            loginInfoMapper.insert(loginInfo)                       ;
            System.out.println("初始化管理员用户成功")               ;
        }
    }

    public LoginInfo getLoginInfoById(Long id)
    {
        return loginInfoMapper.selectByPrimaryKey(id);
    }

    public PageInfo getIdByDimUsername(String text)
    {
        PageHelper.startPage(1,5);
        List<LoginInfo> list =loginInfoMapper.getIdByDimUsername(text);
        return PageUtil.returnPageInfo(list);
    }

}

